<route lang="json5" type="page">
  {
    "needLogin": true,
    "style": {
      "navigationBarTitleText": "充值",
    }
  }
</route>

<script lang="ts" setup>
import { computed, ref } from 'vue'
import { onLoad } from '@dcloudio/uni-app'

// 水表信息
const meterInfo = ref({
  meterId: '',
  name: '',
  balance: '0.00',
  remainingElectricity: '0.00',
})

// 当前余额
const currentBalance = ref(0)

// 自定义充值金额
const customAmount = ref('')

// 预设充值金额
const presetAmounts = [200, 500, 1000, 2000]

// 选中的充值金额
const selectedAmount = ref<number | null>(presetAmounts[0])

// 支付方式
const paymentMethod = ref('wechat')
const paymentMethods = [
  { value: 'wechat', label: '微信支付', icon: 'home' },
]

onLoad((options: any) => {
  if (options) {
    meterInfo.value = {
      meterId: options.meterId || '',
      name: options.name || '',
      balance: options.balance || '0.00',
      remainingElectricity: options.remainingElectricity || '0.00',
    }
    currentBalance.value = Number.parseFloat(options.balance || 0)
  }
})

// 计算最终充值金额
const finalAmount = computed(() => {
  if (customAmount.value) {
    return Number(customAmount.value)
  }
  return selectedAmount.value || 0
})

// 计算充值后余额
const balanceAfterRecharge = computed(() => {
  return currentBalance.value + finalAmount.value
})

// 选择预设金额
function selectPresetAmount(amount: number) {
  selectedAmount.value = amount
  customAmount.value = ''
}

// 输入自定义金额时清除预设选择
function onCustomAmountInput() {
  selectedAmount.value = null
}

// 充值按钮状态
const canRecharge = computed(() => {
  return finalAmount.value > 0
})

// 提交充值
function submitRecharge() {
  if (!canRecharge.value) {
    uni.showToast({ title: '请选择充值金额', icon: 'none' })
    return
  }

  if (finalAmount.value < 1) {
    uni.showToast({ title: '充值金额不能少于1元', icon: 'none' })
    return
  }

  if (finalAmount.value > 10000) {
    uni.showToast({ title: '单次充值金额不能超过10000元', icon: 'none' })
    return
  }

  // 模拟支付流程
  uni.showModal({
    title: '确认充值',
    content: `充值金额：¥${finalAmount.value}\n支付方式：${paymentMethods.find(p => p.value === paymentMethod.value)?.label}\n\n确认要充值吗？`,
    success: (res) => {
      if (res.confirm) {
        uni.showLoading({ title: '支付中...' })

        // 模拟支付请求
        setTimeout(() => {
          uni.hideLoading()
          uni.showToast({ title: '充值成功', icon: 'success' })

          // 延迟返回
          setTimeout(() => {
            uni.navigateTo({ url: '/pages-user/user/waterRecharge/success' })
          }, 500)
        }, 2000)
      }
    },
  })
}
</script>

<template>
  <view class="recharge-page min-h-screen py-3">
    <!-- 顶部信息 -->
    <wd-card custom-class="mx-3 mt-3 !p-0">
      <view class="p-4">
        <view class="flex items-baseline">
          <text class="text-gray-600">
            剩余电量：
          </text>
          <text
            class="text-2xl font-bold"
            :class="{ 'text-red-500': parseFloat(meterInfo.remainingElectricity) < 0, 'text-green-500': parseFloat(meterInfo.remainingElectricity) > 0 }"
          >
            {{ meterInfo.remainingElectricity }}
          </text>
          <text class="ml-1 text-sm font-bold">
            度
          </text>
        </view>
      </view>
      <view class="flex items-center justify-between border-t border-gray-100 p-3 text-xs text-gray-500">
        <text>电表名称: {{ meterInfo.name }}</text>
        <text>表号: {{ meterInfo.meterId }}</text>
        <text>余额: {{ meterInfo.balance }}</text>
      </view>
    </wd-card>

    <!-- 充值金额选择 -->
    <wd-card custom-class="mx-3 mt-3">
      <view class="py-2">
        <view class="mb-4 text-lg text-black font-medium">
          充值金额
        </view>

        <!-- 预设金额 -->
        <view class="grid grid-cols-2 mb-4 gap-3">
          <view
            v-for="amount in presetAmounts"
            :key="amount"
            class="cursor-pointer border-2 rounded-lg px-4 py-3 text-center transition-all"
            :class="selectedAmount === amount ? 'border-blue-500 bg-blue-100 text-blue-600' : 'border-gray-200 text-gray-700'"
            @click="selectPresetAmount(amount)"
          >
            <view class="text-lg font-medium">
              ¥{{ amount }}
            </view>
          </view>
        </view>

        <!-- 自定义金额输入 -->
        <view class="mb-4">
          <wd-input
            v-model="customAmount"
            type="digit"
            size="large"
            placeholder="输入其他金额"
            prefix-icon="money-circle"
            clearable
            input-mode="decimal"
            @input="onCustomAmountInput"
          >
            <template #prefix>
              <text class="mr-2 text-gray-500">
                ¥
              </text>
            </template>
          </wd-input>
          <view class="mt-2 text-xs text-gray-400">
            充值金额范围：1-10000元
          </view>
        </view>

        <!-- 充值后余额预览 -->
        <view v-if="finalAmount > 0" class="rounded-lg bg-blue-100 p-3 text-sm">
          <view class="flex items-center justify-between">
            <text class="text-gray-600">
              充值后余额
            </text>
            <text class="text-blue-600 font-medium">
              ¥{{ balanceAfterRecharge.toFixed(2) }}
            </text>
          </view>
        </view>
      </view>
    </wd-card>

    <!-- 支付方式 -->
    <wd-card custom-class="mx-3 mt-3">
      <view class="pb-2">
        <view class="mb-4 text-lg font-medium">
          支付方式
        </view>

        <wd-radio-group v-model="paymentMethod">
          <view v-for="method in paymentMethods" :key="method.value" class="mb-3">
            <wd-cell>
              <template #icon>
                <wd-icon :name="method.icon" size="36rpx" />
              </template>
              <template #title>
                <text class="ml-2">
                  {{ method.label }}
                </text>
              </template>
              <template #right-icon>
                <wd-icon name="check-circle-filled" size="22px" color="green" />
              </template>
            </wd-cell>
          </view>
        </wd-radio-group>
      </view>
    </wd-card>

    <!-- 充值按钮 -->
    <view class="fixed bottom-0 left-0 right-0 border-t border-gray-200 bg-white p-4 pb-safe">
      <wd-button
        block
        type="primary"
        size="large"
        :disabled="!canRecharge"
        @click="submitRecharge"
      >
        <text v-if="finalAmount > 0">
          确认充值 ¥{{ finalAmount.toFixed(2) }}
        </text>
        <text v-else>
          请选择充值金额
        </text>
      </wd-button>
    </view>

    <!-- 底部安全占位 -->
    <view class="h-20" />
  </view>
</template>

    <style scoped>

    </style>
